package com.wstuo.common.security.dto;

import com.wstuo.common.dto.BaseDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.entity.Function;
import com.wstuo.common.security.service.ComparatorFunction;
import com.wstuo.common.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * class FunctionTreeDTO.
 * 
 * @author will
 * 
 */
@SuppressWarnings("serial")
public class FunctionTreeDTO extends BaseDTO {
	/**
	 * tree data.
	 */
	private String data;

	/**
	 * tree node's state(open or close).
	 */
	private String state;

	/**
	 * a map for node's attrs.
	 */
	private Map<String, String> attr = new HashMap<String, String>();

	/**
	 * node's children.
	 */
	private List<FunctionTreeDTO> children = new ArrayList<FunctionTreeDTO>();

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public Map<String, String> getAttr() {
		return attr;
	}

	public void setAttr(Map<String, String> attributes) {
		this.attr = attributes;
	}

	public List<FunctionTreeDTO> getChildren() {
		return children;
	}

	public void setChildren(List<FunctionTreeDTO> children) {
		this.children = children;
	}

	/**
	 * Convert domain entity object into data transfer object.
	 * 
	 * @param entity
	 *            Organization
	 * @param dto
	 *            OrganizationTreeDTO
	 */
	public static void entity2dto(Function entity, FunctionTreeDTO dto) {
		try {
			if (entity.getDataFlag() != 99) {
				dto.setData(entity.getResName());
				dto.getAttr().put("resNo", "" + entity.getResNo());
				dto.getAttr().put("resName", "" + entity.getResName());
				dto.getAttr().put("resCode", "" + entity.getResCode());
				dto.getAttr().put("resIcon", "" + entity.getResIcon());
				dto.getAttr().put("resUrl", "" + entity.getResUrl());
				dto.getAttr().put("sequence", "" + entity.getSequence());

				if (!CollectionUtils.isEmpty(entity.getSubFunctions())) {
					List<Function> functionList = new ArrayList<Function>();
					for (Function function : entity.getSubFunctions()) {
						functionList.add(function);
					}
					ComparatorFunction comparator = new ComparatorFunction();
					Collections.sort(functionList, comparator);
					for (Function ctg : functionList) {
						FunctionTreeDTO ctgDTO = new FunctionTreeDTO();
						FunctionTreeDTO.entity2dto(ctg, ctgDTO);
						dto.getChildren().add(ctgDTO);
					}
				}

			}
		} catch (Exception ex) {
			throw new ApplicationException("Exception caused while converting Entity into DTO: ", ex);
		}
	}
}
